package com.meiyuetao.myt.pairui.web.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import lab.s2jh.core.annotation.MetaData;
import lab.s2jh.core.pagination.GroupPropertyFilter;
import lab.s2jh.core.pagination.PropertyFilter;
import lab.s2jh.core.pagination.PropertyFilter.MatchType;
import lab.s2jh.core.service.BaseService;
import lab.s2jh.core.util.DateUtils;
import lab.s2jh.core.web.view.OperationResult;
import lab.s2jh.sys.entity.AttachmentFile;
import lab.s2jh.sys.service.AttachmentFileService;
import lab.s2jh.web.action.BaseController;

import org.apache.commons.collections.CollectionUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.struts2.rest.HttpHeaders;
import org.springframework.beans.factory.annotation.Autowired;

import com.meiyuetao.myt.customer.entity.CustomerProfile;
import com.meiyuetao.myt.customer.service.CustomerProfileService;
import com.meiyuetao.myt.md.entity.Box;
import com.meiyuetao.myt.md.entity.Commodity;
import com.meiyuetao.myt.md.service.BoxService;
import com.meiyuetao.myt.md.service.CommodityService;
import com.meiyuetao.myt.sale.entity.BoxOrder;
import com.meiyuetao.myt.sale.entity.BoxOrder.BoxOrderSplitPayModeEnum;
import com.meiyuetao.myt.sale.entity.BoxOrderDetail;
import com.meiyuetao.myt.sale.entity.BoxOrderDetailCommodity;
import com.meiyuetao.myt.sale.service.BoxOrderDetailService;
import com.meiyuetao.myt.sale.service.BoxOrderService;
import com.meiyuetao.myt.vip.entity.VipCustomerProfile;
import com.meiyuetao.myt.vip.service.VipCustomerProfileService;
import com.meiyuetao.myt.vip.service.VipLevelService;

@MetaData("ERP派瑞订单附件管理")
public class PairuiOrderFileController extends BaseController<AttachmentFile, String> {

    @Autowired
    private AttachmentFileService attachmentFileService;
    @Autowired
    private BoxService boxService;
    @Autowired
    private BoxOrderService boxOrderService;
    @Autowired
    private BoxOrderDetailService boxOrderDetailService;
    @Autowired
    private CommodityService commodityService;
    @Autowired
    private CustomerProfileService customerProfileService;
    @Autowired
    private VipLevelService vipLevelService;
    @Autowired
    private VipCustomerProfileService vipCustomerProfileService;

    private File file;

    @Override
    protected void checkEntityAclPermission(AttachmentFile arg0) {
    }

    @Override
    protected BaseService<AttachmentFile, String> getEntityService() {
        return attachmentFileService;
    }

    public HttpHeaders upLoadNew() {
        return buildDefaultHttpHeaders("inputBasic");
    }

    @MetaData(value = "派瑞订单上传")
    public HttpHeaders upload() throws FileNotFoundException, IOException {
        System.out.println(file.toString());
        readExcel(file);
        setModel(OperationResult.buildSuccessResult("导入完成"));
        return buildDefaultHttpHeaders();
    }

    /**
     * 读取excel文件，转存为订单对象
     * 
     * @param file
     *            excel文件(路径+文件)
     * @return
     * @throws IOException
     * @throws FileNotFoundException
     */
    public void readExcel(File file) throws FileNotFoundException, IOException {
        Box box = boxService.getTop();
        List<BoxOrder> orders = new ArrayList<BoxOrder>();
        XSSFWorkbook book = new XSSFWorkbook(new FileInputStream(file));
        XSSFSheet sheet0 = book.getSheetAt(0);
        XSSFSheet sheet1 = book.getSheetAt(1);
        XSSFRow title0 = sheet0.getRow(0);
        int rowSize0 = title0.getLastCellNum();
        XSSFRow title1 = sheet1.getRow(0);
        int rowSize1 = title1.getLastCellNum();
        // 判断主数据和明细数据
        XSSFSheet mSheet;
        XSSFSheet dSheet;
        if (rowSize0 > rowSize1) {
            mSheet = sheet0;
            dSheet = sheet1;
        } else {
            mSheet = sheet1;
            dSheet = sheet0;
        }
        XSSFRow mtitle = mSheet.getRow(0);
        XSSFRow dtitle = dSheet.getRow(0);
        int colIndex = 0;
        int colOdrNum = 0;
        int colOdrTim = 3;
        int colRecPer = 6;
        int colOriAmo = 9;
        int colActAmo = 10;
        int colDelPro = 14;
        int colDelCit = 15;
        int colDelStr = 16;
        int colDelAdd = 17;
        int colPosCod = 22;
        int colMobPho = 23;
        int colPayVou = 41;
        int colRefAmo = 51;
        int colSeq = 55;
        int cloPos = 65;
        for (Iterator<Cell> it = mtitle.cellIterator(); it.hasNext();) {
            colIndex++;
            String cellString = it.next().toString();
            if ("订单号".equals(cellString)) {
                colOdrNum = colIndex - 1;
                continue;
            }
            if ("成交时间".equals(cellString)) {
                colOdrTim = colIndex - 1;
                continue;
            }
            if ("收件人".equals(cellString)) {
                colRecPer = colIndex - 1;
                continue;
            }
            if ("实际结算".equals(cellString)) {
                colOriAmo = colIndex - 1;
                continue;
            }
            if ("应收合计".equals(cellString)) {
                colActAmo = colIndex - 1;
                continue;
            }
            if ("州省".equals(cellString)) {
                colDelPro = colIndex - 1;
                continue;
            }
            if ("区市".equals(cellString)) {
                colDelCit = colIndex - 1;
                continue;
            }
            if ("区镇".equals(cellString)) {
                colDelStr = colIndex - 1;
                continue;
            }
            if ("地址".equals(cellString)) {
                colDelAdd = colIndex - 1;
                continue;
            }
            if ("邮编".equals(cellString)) {
                colPosCod = colIndex - 1;
                continue;
            }
            if ("电话".equals(cellString)) {
                colMobPho = colIndex - 1;
                continue;
            }
            if ("支付单号".equals(cellString)) {
                colPayVou = colIndex - 1;
                continue;
            }
            if ("补偿退款".equals(cellString)) {
                colRefAmo = colIndex - 1;
                continue;
            }
            if ("原始单号".equals(cellString)) {
                colSeq = colIndex - 1;
                continue;
            }
            if ("实际邮资".equals(cellString)) {
                cloPos = colIndex - 1;
                continue;
            }
        }
        int dcolIndex = 0;
        int dcolOdrNum = 2;
        int dcolActAmo = 4;
        int dcolBoxTit = 5;
        int dcolPri = 6;
        int dcolPayAmo = 10;
        int dcolFic = 11;
        int dcolLogNo = 13;
        int dcolLogNam = 14;
        int dcolOriAmo = 15;
        int dcolQua = 19;
        int dcolDisAmo = 22;
        for (Iterator<Cell> it = dtitle.cellIterator(); it.hasNext();) {
            dcolIndex++;
            String dcellString = it.next().toString();
            if ("订单编号".equals(dcellString)) {
                dcolOdrNum = dcolIndex - 1;
                continue;
            }
            if ("实际结算".equals(dcellString)) {
                dcolActAmo = dcolIndex - 1;
                continue;
            }
            if ("品名".equals(dcellString)) {
                dcolBoxTit = dcolIndex - 1;
                continue;
            }
            if ("价格".equals(dcellString)) {
                dcolPri = dcolIndex - 1;
                continue;
            }
            if ("合计".equals(dcellString)) {
                dcolPayAmo = dcolIndex - 1;
                continue;
            }
            if ("货品编号".equals(dcellString)) {
                dcolFic = dcolIndex - 1;
                continue;
            }
            if ("物流单号".equals(dcellString)) {
                dcolLogNo = dcolIndex - 1;
                continue;
            }
            if ("物流方式".equals(dcellString)) {
                dcolLogNam = dcolIndex - 1;
                continue;
            }
            if ("成本".equals(dcellString)) {
                dcolOriAmo = dcolIndex - 1;
                continue;
            }
            if ("数量".equals(dcellString)) {
                dcolQua = dcolIndex - 1;
                continue;
            }
            if ("优惠".equals(dcellString)) {
                dcolDisAmo = dcolIndex - 1;
                continue;
            }
        }
        for (int i = 1, j = 1; i < mSheet.getPhysicalNumberOfRows(); i++) {
            XSSFRow row = mSheet.getRow(i);
            BoxOrder order = boxOrderService.findByOrderSeq(row.getCell(colSeq).toString().split("\\.")[0]);
            if (order == null) {
                order = new BoxOrder();
            }
            // 订单号
            order.setOrderSeq(row.getCell(colSeq).toString().split("\\.")[0]);
            // 下单时间
            order.setOrderTime(DateUtils.parseDate(row.getCell(colOdrTim).toString()));
            // 省
            order.setDeliveryProvince(row.getCell(colDelPro).toString());
            // 市
            order.setDeliveryCity(row.getCell(colDelCit).toString());
            // 区
            order.setDeliveryStreet(row.getCell(colDelStr).toString());
            // 收货地址
            order.setDeliveryAddr(row.getCell(colDelAdd).toString());
            // 邮编
            order.setPostCode(row.getCell(colPosCod).toString());
            // 手机
            order.setMobilePhone(row.getCell(colMobPho).toString());
            // 收货人姓名
            order.setReceivePerson(row.getCell(colRecPer).toString());
            // 应收金额
            order.setActualAmount(BigDecimal.valueOf(Double.valueOf(row.getCell(colActAmo).toString())));
            // 原始金额
            order.setOriginalAmount(BigDecimal.valueOf(Double.valueOf(row.getCell(colOriAmo).toString())));
            // 支付凭证
            order.setPayVoucher(row.getCell(colPayVou).toString());
            // 积分
            order.setScore(0);
            // 分期类型
            order.setSplitPayMode(BoxOrderSplitPayModeEnum.NO);
            // 订单需要支付的保证金
            order.setCautionMoneyNeed(BigDecimal.ZERO);
            // 订单实际支付的保证金
            order.setCautionMoneyActual(BigDecimal.ZERO);
            // 邮费
            order.setPostage(BigDecimal.valueOf(Double.valueOf(row.getCell(cloPos).toString())));
            // 实际用户已支付总额
            order.setActualPayedAmount(BigDecimal.valueOf(Double.valueOf(row.getCell(colOriAmo).toString())));
            // 已退款金额
            order.setRefundAmount(BigDecimal.valueOf(Double.valueOf(row.getCell(colRefAmo).toString())));
            // 关联用户表
            GroupPropertyFilter groupPropertyFilter = GroupPropertyFilter.buildDefaultAndGroupFilter();
            groupPropertyFilter.append(new PropertyFilter(MatchType.EQ, "mobilePhone", order.getMobilePhone()));
            groupPropertyFilter.append(new PropertyFilter(MatchType.EQ, "trueName", order.getReceivePerson()));
            List<CustomerProfile> customerProfiles = customerProfileService.findByFilters(groupPropertyFilter);
            if (CollectionUtils.isEmpty(customerProfiles)) {
                CustomerProfile customer = new CustomerProfile();
                VipCustomerProfile vipCustomerProfile = new VipCustomerProfile();
                customer.setTrueName(order.getReceivePerson());
                customer.setMobilePhone(order.getMobilePhone());
                customer.setCustomerFrom("NONE");
                customerProfileService.save(customer);
                vipCustomerProfile.setCustomerProfile(customer);
                vipCustomerProfile.setVipLevel(vipLevelService.findOne(Long.valueOf(1)));
                vipCustomerProfileService.save(vipCustomerProfile);
                customerProfiles.add(customer);
            }
            order.setCustomerProfile(customerProfiles.get(0));
            String orderNum = row.getCell(colOdrNum).toString();
            List<BoxOrderDetail> lstOrderDetails = order.getBoxOrderDetails();
            for (int k = 0; j < dSheet.getPhysicalNumberOfRows(); j++, k++) {
                XSSFRow detailRow = dSheet.getRow(j);
                String dOrderNum = detailRow.getCell(dcolOdrNum).toString();
                if (orderNum.equals(dOrderNum)) {
                    String sn = String.valueOf(100 + 10 * k);
                    BoxOrderDetail orderDetail = boxOrderDetailService.findByBoxOrderAndSn(order, sn);
                    if (orderDetail == null) {
                        orderDetail = new BoxOrderDetail();
                    }
                    orderDetail.setBoxOrder(order);
                    orderDetail.setBox(box);
                    orderDetail.setCustomerProfile(customerProfiles.get(0));
                    orderDetail.setSn(sn);
                    // 盒子名
                    orderDetail.setBoxTitle(detailRow.getCell(dcolBoxTit).toString());
                    // 价格
                    orderDetail.setPrice(BigDecimal.valueOf(Double.valueOf(detailRow.getCell(dcolPri).toString())));
                    // 数量
                    orderDetail.setQuantity(Integer.valueOf(detailRow.getCell(dcolQua).toString().split("\\.")[0]));
                    // 发货物流单号
                    orderDetail.setLogisticsNo(detailRow.getCell(dcolLogNo).toString());
                    // 发货物流公司
                    orderDetail.setLogisticsName(detailRow.getCell(dcolLogNam).toString());
                    // 原价金额
                    orderDetail.setOriginalAmount(BigDecimal.valueOf(Double.valueOf(detailRow.getCell(dcolOriAmo).toString())));
                    // 销售折扣金额
                    orderDetail.setDiscountAmount(BigDecimal.valueOf(Double.valueOf(detailRow.getCell(dcolDisAmo).toString())));
                    // 实际应付款金额
                    orderDetail.setActualAmount(BigDecimal.valueOf(Double.valueOf(detailRow.getCell(dcolActAmo).toString())));
                    // 行项付款金额
                    orderDetail.setPayAmount(BigDecimal.valueOf(Double.valueOf(detailRow.getCell(dcolPayAmo).toString())));
                    // 商品编号
                    orderDetail.setFicno(detailRow.getCell(dcolFic).toString());
                    // 订单明细商品明细
                    List<BoxOrderDetailCommodity> boxOrderDetailCommodities = orderDetail.getBoxOrderDetailCommodities();
                    BoxOrderDetailCommodity boxOrderDetailCommodity = new BoxOrderDetailCommodity();
                    boxOrderDetailCommodity.setBox(box);
                    boxOrderDetailCommodity.setBoxOrder(order);
                    boxOrderDetailCommodity.setBoxOrderDetail(orderDetail);
                    Commodity commodity = commodityService.findByErpProductId(detailRow.getCell(dcolFic).toString(), orderDetail);
                    boxOrderDetailCommodity.setCommodity(commodity);
                    boxOrderDetailCommodity.setBoxVersion(box.getVersion());
                    boxOrderDetailCommodity.setCommodityVersion(commodity.getVersion());
                    boxOrderDetailCommodities.add(boxOrderDetailCommodity);
                    orderDetail.setBoxOrderDetailCommodities(boxOrderDetailCommodities);
                    lstOrderDetails.add(orderDetail);
                } else {
                    break;
                }
            }
            order.setBoxOrderDetails(lstOrderDetails);
            orders.add(order);
            boxOrderService.save(order);
        }
    }

    public File getFile() {
        return file;
    }

    public void setFile(File file) {
        this.file = file;
    }

}
